/**
  普通话等级考试-编辑名单设置
*/
<template>
  <div class="list-setting">
    <div v-show="activeName === 'studentListing'">
      <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="100px">
        <el-row :gutter="24" style="height: 50px;">
          <el-col :span="8">
            <el-form-item :label="$t('mandarin.schoolStatus')">
              <el-select v-model="studentQueryForm.condition.leaveSchoolList" multiple clearable style="width: 100%">
                <el-option
                  v-for="item in options.leaveSchool"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('mandarin.studentStatus')">
              <el-select v-model="studentQueryForm.condition.registrationStatusList" multiple clearable style="width: 100%">
                <el-option
                  v-for="item in options.registrationStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('mandarin.inSchoolMethod')">
              <el-select v-model="studentQueryForm.condition.enrolMethodsList" multiple clearable style="width: 100%">
                <el-option
                  v-for="item in options.enrolMethods"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('englishScoreManage.gradeSchool')">
              <el-select v-model="studentQueryForm.condition.gradeList" clearable multiple style="width: 100%">
                <el-option
                  v-for="item in options.gradeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
    </div>
    <div v-show="activeName === 'choosedListing'">
      <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="100px">
        <el-row :gutter="24" style="height: 50px;">
          <el-col :span="8">
            <el-form-item :label="$t('mandarin.schoolStatus')">
              <el-select v-model="choosedQueryForm.condition.leaveSchool" clearable style="width: 100%">
                <el-option
                  v-for="item in options.leaveSchool"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('mandarin.studentStatus')">
              <el-select v-model="choosedQueryForm.condition.registrationStatus" clearable style="width: 100%">
                <el-option
                  v-for="item in options.registrationStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('mandarin.inSchoolMethod')">
              <el-select v-model="choosedQueryForm.condition.enrolMethods" clearable style="width: 100%">
                <el-option
                  v-for="item in options.enrolMethods"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('englishScoreManage.gradeSchool')">
              <el-select v-model="choosedQueryForm.condition.gradeList" clearable multiple style="width: 100%">
                <el-option
                  v-for="item in options.gradeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
    </div>
    <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
      <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane :label="$t('mandarin.studentListing')" name="studentListing">
            <div class="edu-opertion-bar sub-title">
              <div class="float-left">
                <el-input
                  v-model.trim="studentQueryForm.condition.name"
                  :placeholder="$t('subjectCompetitionBase.studentIdOrName')"
                  style="width:250px"
                  @keyup.enter.native="onSubmit">
                    <i slot="suffix"
                      class="el-icon-search"
                      style="margin-top:10px;cursor:pointer"
                      @click="onSubmit">
                    </i>
                </el-input>
              </div>
              <div class="float-right" style="display: flex;">
                <el-button v-if="permitToAdd" type="primary" @click="addListing()">{{$t('subjectCompetitionBase.add')}}</el-button>
              </div>
            </div>
            <self-edu-table ref="studentTable" :pagination="false" :order='false' :tooltipEffect="tooltipEffect" :getRowKey="getRowKey" stripe :data="stuListingData" size="mini" @selection-change="changeStuList">
              <edu-table-column :label="$t('subjectCompetitionBase.studentId')" prop="studentId"></edu-table-column>
              <edu-table-column :label="$t('subjectCompetitionBase.name')" prop="name"></edu-table-column>
              <edu-table-column :label="$t('subjectCompetitionBase.sex')" prop="sexI18n"></edu-table-column>
              <edu-table-column :label="$t('subjectCompetitionBase.college')" prop="facultyI18n"></edu-table-column>
              <edu-table-column :label="$t('mandarin.schoolStatus')" prop="leaveSchoolI18n"></edu-table-column>
              <edu-table-column :label="$t('mandarin.studentStatus')" prop="registrationStatusI18n"></edu-table-column>
              <!-- <edu-table-column :label="$t('mandarin.sourceSchool')" prop="sourceSchoolStr"></edu-table-column> -->
            </self-edu-table>
            <el-row type="flex" class="row-bg" justify="end">
              <el-col>
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="studentQueryForm.pageNum_"
                  :page-sizes="[20, 40, 80, 100]"
                  :page-size="studentQueryForm.pageSize_"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="studentQueryForm.total_"
                  style="float:right;margin-top:10px"
                ></el-pagination>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane :label="$t('mandarin.choosedListing')" name="choosedListing">
            <div class="edu-opertion-bar sub-title">
              <div class="float-left">
                <el-input
                  v-model.trim="choosedQueryForm.condition.studentId"
                  :placeholder="$t('subjectCompetitionBase.studentIdOrName')"
                  style="width:250px"
                  @keyup.enter.native="onSubmit">
                    <i slot="suffix"
                      class="el-icon-search"
                      style="margin-top:10px;cursor:pointer"
                      @click="onSubmit">
                    </i>
                </el-input>
              </div>
              <div class="float-right" style="display: flex;">
                <el-button v-if="permitToDelete" type="primary" @click="deleteListing()">{{$t('common.btn.delete')}}</el-button>
              </div>
            </div>
            <self-edu-table ref="choosedTable" :pagination="false" :order='true' :tooltipEffect="tooltipEffect" stripe :data="currentPageData" :getRowKey="getRowKey" size="mini" @selection-change="changeChoosedList">
              <edu-table-column :label="$t('subjectCompetitionBase.studentId')" prop="studentId"></edu-table-column>
              <edu-table-column :label="$t('subjectCompetitionBase.name')" prop="name"></edu-table-column>
              <edu-table-column :label="$t('subjectCompetitionBase.sex')" prop="sexI18n"></edu-table-column>
              <edu-table-column :label="$t('subjectCompetitionBase.college')" prop="facultyI18n"></edu-table-column>
              <edu-table-column :label="$t('mandarin.schoolStatus')" prop="leaveSchoolI18n"></edu-table-column>
              <edu-table-column :label="$t('mandarin.studentStatus')" prop="registrationStatusI18n"></edu-table-column>
              <!-- <edu-table-column :label="$t('mandarin.sourceSchool')" prop="sourceSchoolStr"></edu-table-column> -->
            </self-edu-table>
            <el-row type="flex" class="row-bg" justify="end">
              <el-col>
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="choosedQueryForm.pageNum_"
                  :page-sizes="[20, 40, 80, 100]"
                  :page-size="choosedQueryForm.pageSize_"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="choosedQueryForm.total_"
                  style="float:right;margin-top:10px"
                ></el-pagination>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div v-if="activeName === 'choosedListing'" style="border-top: 1px solid #ccc;padding: 10px 0 10px 0;margin: 10px 0;">
        <div class="float-right">
          <el-button @click="cancelOperate()">{{ $t('common.btn.cancel') }}</el-button>
          <!-- <el-button type="primary" @click="confirmOperate()">{{ $t('common.btn.confirm') }}</el-button> -->
        </div>
      </div>
    </el-card>
  </div>
</template>
<script>
  import UTILS from "common/src/utils/utils";
  import { queryDic } from "common/src/api/dictionary";
  import selfEduTable from 'common/src/views/graduateStudent/common/selfEduTable';
  import subjectCompetitionApi from 'common/src/api/subjectCompetition/subjectCompetition';
  export default {
    components: {
      'self-edu-table': selfEduTable
    },
    data () {
      return {
        activeName: 'studentListing',
        permitToAdd: true,
        permitToDelete: true,
        // permitToAdd: false,
        // permitToDelete: false,
        studentQueryForm: {
          pageNum_: 1,
          pageSize_: 20,
          total_: 0,
          condition: {
            leaveSchoolList: [],
            registrationStatusList: [],
            enrolMethodsList: [],
            gradeList: [],
            name: ''
          }
        },
        choosedQueryForm: {
          pageNum_: 1,
          pageSize_: 20,
          total_: 0,
          condition: {
            leaveSchool: '',
            registrationStatus: '',
            enrolMethods: '',
            gradeList: [],
            studentId: ''
          }
        },
        options: {
          sex: [],
          gradeList: [],
          faculty: [],
          leaveSchool: [],
          registrationStatus: [],
          enrolMethods: []
        },
        stuListingData: [],
        multiStuList: [],
        choosedListingData: [
        ],
        multiChoosedListing: [],
        key: '',
        copyChoosedListingData: [],
        totalPage: 0,
        currentPageData: [],
        choosedDataList: [],
        deleteArray: []
      }
    },
    props: {
      editConfirmData: {
        type: Array,
        default: () => {}
      },
      examIdrow:{
        type: String,
        default: () => {}
      }
    },
    computed: {

    },
    created() {
      this.initOptions()
      subjectCompetitionApi.getCurrentDate().then(res => {
        this.options.gradeList = []
        this.studentQueryForm.condition.gradeList = [res.data.calendarYear]
        this.calendarYear = res.data.calendarYear
        res.data.calendarYearList.forEach(el =>{
          this.options.gradeList.push({
              value: el,
              label: el
            })

        })
      }).then(() => {
        this.onSubmit()
      })
      this.setCurrentPageData()
    },
    methods: {
      async initOptions() {
        // 筛选条件字典查询
        let data = {
          lang: this.$store.getters.language || "cn",
          type: "allChild",
          keys: [
            "G_XBIE", // 性别
            "X_YX", // 学院
            "K_ZXZT", // 在校状态
            "G_XJZT", // 学籍状态
            "X_RXFS" // 入学方式
          ]
        };
        await queryDic(data).then(res => {
          UTILS.fillSelect(
            {
              sex: "G_XBIE", // 性别
              faculty: "X_YX", // 学院
              leaveSchool: "K_ZXZT", // 在校状态
              registrationStatus: "G_XJZT", // 学籍状态
              enrolMethods: "X_RXFS" // 入学方式
            },
            res.data,
            this.options
          );
        });
      },
      getRowKey(row) {
        return row.studentId
      },
      //已选名单查询
      setCurrentPageData() {
        let obj = {
            condition:{
              leaveSchoolList:[],
              registrationList:[],
              enrolMethodsList:[],
              currentGradeList:[],
              examId:this.examIdrow,
            },
            pageNum_:this.choosedQueryForm.pageNum_,
            pageSize_:this.choosedQueryForm.pageSize_
          };
          obj.condition.leaveSchoolList=this.choosedQueryForm.condition.leaveSchool;
          obj.condition.registrationList=this.choosedQueryForm.condition.registrationStatus;
          obj.condition.enrolMethodsList=this.choosedQueryForm.condition.enrolMethods;
          obj.condition.currentGradeList=this.choosedQueryForm.condition.gradeList;
          obj.condition.studentId=this.choosedQueryForm.condition.studentId;
          subjectCompetitionApi.selectedStudent(obj).then((res) => {
            if (res.code === 200) {
              this.currentPageData=res.data.list;
              this.choosedQueryForm.total_=res.data.total_;
            } else {
              //this.$message({ type: 'error', message: res.msg })
            }
          })
      },
      clearSereset() {
        this.activeName = 'studentListing'
        // if (this.activeName === 'studentListing') {
          this.studentQueryForm.condition.leaveSchoolList = []
          this.studentQueryForm.condition.registrationStatusList = []
          this.studentQueryForm.condition.enrolMethodsList = []
          this.studentQueryForm.condition.name = ''
          this.studentQueryForm.condition.excludeNewestAndExchange = 1
          this.studentQueryForm.condition.gradeList = [this.calendarYear]
          this.choosedQueryForm.condition.leaveSchool = ''
          this.choosedQueryForm.condition.registrationStatus = ''
          this.choosedQueryForm.condition.enrolMethods = ''
          this.choosedQueryForm.condition.name = ''
          this.choosedQueryForm.condition.gradeList = []
          this.onSubmit()
        // }
      },
      reset() {
        if (this.activeName === 'studentListing') {
          this.studentQueryForm.condition.leaveSchoolList = []
          this.studentQueryForm.condition.registrationStatusList = []
          this.studentQueryForm.condition.enrolMethodsList = []
          this.studentQueryForm.condition.name = ''
          this.studentQueryForm.condition.excludeNewestAndExchange = 1
          this.studentQueryForm.condition.gradeList = [this.calendarYear]
          // Object.keys(this.studentQueryForm.condition).forEach(key => this.studentQueryForm.condition[key] = '');
        } else {
          // Object.keys(this.choosedQueryForm.condition).forEach(key => this.choosedQueryForm.condition[key] = '');
          this.choosedQueryForm.condition.leaveSchool = ''
          this.choosedQueryForm.condition.registrationStatus = ''
          this.choosedQueryForm.condition.enrolMethods = ''
          //this.choosedQueryForm.condition.name = '';
          this.choosedQueryForm.condition.studentId='';
          // this.choosedQueryForm.condition.excludeNewestAndExchange = 1
          this.choosedQueryForm.condition.gradeList = []
        }
        this.onSubmit();
      },
      getListData() {
        if (this.activeName === 'choosedListing') {
          let queryForm = JSON.parse(JSON.stringify(this.choosedQueryForm))
          let initStatus = true
          initStatus = Object.keys(this.choosedQueryForm.condition).every(item => {
            return !this.choosedQueryForm.condition[item]
          })
          if (initStatus) {
            this.choosedListingData = this.copyChoosedListingData
            let obj = {};
            let peon = this.choosedListingData.reduce((cur,next) => {
              obj[next.studentId] ? "" : obj[next.studentId] = true && cur.push(next);
              return cur;
            },[])
            this.choosedListingData = peon
          } else {
            this.choosedListingData = this.copyChoosedListingData.filter((item, index, array) => {
              let isFilterName = true
              let isFilterLeaveSchool = true
              let isFilterRegistStatus = true
              let isFilterEnrolMethods = true
              let isFilterGrade = true
              if (this.choosedQueryForm.condition.name.length > 0) {
                isFilterName = item.name.indexOf(this.choosedQueryForm.condition.name.trim()) > -1 || item.studentId.indexOf(this.choosedQueryForm.condition.name.trim()) > -1
              }
              if (this.choosedQueryForm.condition.leaveSchool.length > 0) {
                isFilterLeaveSchool = item.leaveSchool === this.choosedQueryForm.condition.leaveSchool
              }
              if (this.choosedQueryForm.condition.registrationStatus.length > 0) {
                isFilterRegistStatus = item.registrationStatus === this.choosedQueryForm.condition.registrationStatus
              }
              if (this.choosedQueryForm.condition.enrolMethods.length > 0) {
                isFilterEnrolMethods = item.enrolMethods === this.choosedQueryForm.condition.enrolMethods
              }
              // if (this.choosedQueryForm.condition.grade) {
              //   isFilterGrade = item.grade == this.choosedQueryForm.condition.grade
              // }
              if (this.choosedQueryForm.condition.gradeList.length > 0) {
                this.choosedQueryForm.condition.gradeList.forEach(el => {
                  if (this.choosedQueryForm.condition.gradeList.indexOf(item.grade)>=0) {
                    isFilterGrade = true
                  } else {
                    isFilterGrade = false
                  }

                })
              }
              return isFilterName && isFilterLeaveSchool && isFilterRegistStatus && isFilterEnrolMethods && isFilterGrade
            })
            let obj = {};
            let peon = this.choosedListingData.reduce((cur,next) => {
              obj[next.studentId] ? "" : obj[next.studentId] = true && cur.push(next);
              return cur;
            },[])
            this.choosedListingData = peon
          }
          // this.$refs['choosedTable'].clearSelection()
        } else {
          let queryForm = JSON.parse(JSON.stringify(this.studentQueryForm))
          queryForm.condition['educationTag'] = 1
          queryForm.condition.name = queryForm.condition.name.trim()
          subjectCompetitionApi.selectStudentRoster(queryForm).then((res) => {
            this.stuListingData = res.data.list;
            this.studentQueryForm.total_ = res.data.total_;
          })
        }
      },
      onSubmit() {
        if (this.activeName === 'studentListing') {
          this.studentQueryForm.pageNum_ = 1
        } else {
          this.choosedQueryForm.pageNum_ = 1
        }
        this.getListData()
      },
      handleClick() {
        if (this.activeName === 'studentListing') {
          this.studentQueryForm.pageNum_ = 1
          this.getListData();
        }else{
          this.choosedQueryForm.pageNum_ = 1;
          this.choosedQueryForm.condition.studentId='';
          this.setCurrentPageData();
        }
      },
      unique(arr) {
        const res = new Map();
        return arr.filter((a) => !res.has(a.studentId) && res.set(a.studentId, 1))
      },
      // 添加名单到已选名单
      addListing(){
          let obj = {
            examCnSpeakRole:{
              leaveSchool:'',
              registration:'',
              enrolMethods:'',
              currentGrade:''
            }
          };
          if (this.multiStuList.length == 0) {
            obj.examCnSpeakRole.leaveSchool=this.studentQueryForm.condition.leaveSchoolList.join(',');
            obj.examCnSpeakRole.registration=this.studentQueryForm.condition.registrationStatusList.join(',');
            obj.examCnSpeakRole.enrolMethods=this.studentQueryForm.condition.enrolMethodsList.join(',');
            obj.examCnSpeakRole.currentGrade=this.studentQueryForm.condition.gradeList.join(',');
            obj.studentList=[];
          }else{
            var arr=[];
            arr=this.multiStuList.map(item=>item.studentId);
            var studentList=[];
            for (let i = 0; i < arr.length; i++) {
                var objrow={};
                objrow.studentId=arr[i];
                studentList.push(objrow);
            }
            obj.examCnSpeakRole=null;
            obj.studentList=studentList;
          }
          obj.examId=this.examIdrow;
          subjectCompetitionApi.addStudentRoster(obj).then((res) => {
            if (res.code === 200) {
              this.multiStuList=[];
              this.$refs.studentTable.clearSelection();
              this.getListData();
              this.$message({ type: 'success', message: '成功' })
            } else {
              this.$message({ type: 'error', message: res.msg })
            }
          })
      },
      deleteListing(){
        this.$confirm('确认删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            var arr=[];
            arr=this.multiChoosedListing.map(item=>item.studentId);
            var studentList=[];
            for (let i = 0; i < arr.length; i++) {
                var objrow={};
                objrow.studentId=arr[i];
                studentList.push(objrow);
            }
            let obj={};
            if(this.multiChoosedListing.length>0){
              obj.studentList=studentList;
            }else{
              obj.studentList=[];
            }
            obj.examId=this.examIdrow;
            subjectCompetitionApi.deleteStudent(obj).then((res) => {
                if (res.code === 200) {
                  this.setCurrentPageData();
                  this.$message({ type: 'success', message: '成功' })
                  this.multiChoosedListing=[];
                } else {
                  this.$message({ type: 'error', message: res.msg })
                }
              })

          })
          .catch(() => {
          })


      },
      // 选择学生名单
      changeStuList(val) {
        this.multiStuList = val
      },
      // 选择已选名单
      changeChoosedList(val) {
        this.multiChoosedListing = val
      },
      // 修改每页显示条数
      handleSizeChange(val) {
        if (this.activeName === 'studentListing') {
          this.studentQueryForm.pageSize_ = val
          this.getListData()
        } else {
          this.choosedQueryForm.pageSize_ = val
          this.setCurrentPageData()
        }
      },
      // 修改页数
      handleCurrentChange(val) {
        if (this.activeName === 'studentListing') {
          this.studentQueryForm.pageNum_ = val
          this.getListData()
        } else {
          this.choosedQueryForm.pageNum_ = val
          this.setCurrentPageData()
        }
      },
      // 取消
      cancelOperate() {
        if (!this.editConfirmData || this.editConfirmData.length === 0) {
          this.choosedListingData = []
          this.copyChoosedListingData = []
        } else {
          this.choosedListingData = JSON.parse(JSON.stringify(this.editConfirmData))
          this.setCurrentPageData()
        }
        this.activeName = 'studentListing'
        this.$refs['studentTable'].clearSelection()
        this.$refs['choosedTable'].clearSelection()
        this.studentQueryForm.pageNum_ = 1
        this.onSubmit()
        this.$emit('close-list-setting')
      },
      // 确定
      confirmOperate() {
        this.activeName = 'studentListing'
        this.$refs['studentTable'].clearSelection()
        this.$refs['choosedTable'].clearSelection()
        this.$emit('confirm-list-setting', this.choosedListingData)
        this.$emit('delete-list-setting', this.deleteArray)
        this.studentQueryForm.pageNum_ = 1
        this.onSubmit()
      }
    },
    watch: {
      "editConfirmData": {
        handler(newVal) {
          if (newVal) {
            this.choosedListingData = JSON.parse(JSON.stringify(newVal))
            this.choosedDataList = JSON.parse(JSON.stringify(newVal))
            this.copyChoosedListingData = JSON.parse(JSON.stringify(newVal))
          }
        },
        deep: true,
        immediate: true
      },
      "choosedListingData": {
        handler(newVal) {
          this.choosedQueryForm.pageNum_ = 1
          this.setCurrentPageData()
          this.choosedQueryForm.total_ = newVal.length
        },
        deep: true,
        immediate: true
      }
    }
  }
</script>
<style lang="scss" scoped>
  .list-setting {
    .operate-btn-container {
      border: 0;
      padding: 20px;
      margin: 0;
    }
  }
</style>
